package com.atyjh.reggie.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpStatus;
import com.atyjh.reggie.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 文件的上传与下载
 *
 * @author yjh
 * @since jdk1.8.0_311 2022.06.16
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.img.path}")
    private String basePath;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {

        try {
//        1. 获取文件原始名字
            String originalName = file.getOriginalFilename();
//        2. 获取文件后缀
            String suffix = originalName.substring(originalName.lastIndexOf('.'));
//        3. 使用UUID获得文件新名字
            String realName = UUID.randomUUID() + suffix;

            log.info(basePath + realName);

//        4. 获取文件保存路径
            File newFile = new File(basePath);
            if (!newFile.exists()) {
    //            创建目录
                newFile.mkdir();
            }
//            5. 将文件转存到指定目录下，并赋予新的文件名
            file.transferTo(new File(basePath + realName));

//            返回文件真实名字【等下文件下载的请求要用】
            return Result.success(realName);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.error("上传出错！");
    }


    @GetMapping("/download/method")
    public void download(@RequestParam("name")String name, HttpServletResponse response) {

        FileInputStream is = null;
        ServletOutputStream os = null;

        try {
//            获取文件绝对路径
            String path = basePath + name;
//            获取文件的输入流
            is = new FileInputStream(path);

//            获取响应的输出流
            os = response.getOutputStream();

//            告诉浏览器我要传输的文件是什么类型
            response.setContentType("image/jpeg");

//            创建字节数组【available()表示输入流对应的文件的字节数】
            byte[] bytes = new byte[is.available()];
//            将流读取到字节数组中
            is.read(bytes);

//            将字节数组写回浏览器
            os.write(bytes);
            os.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
//            关闭资源
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("name")String name) {

        try {
//            获取文件的绝对路径
            String path = basePath + name;

//            获取文件的输入流
            FileInputStream is = new FileInputStream(path);

//            将输入流读取到字节数组中
            byte[] bytes = new byte[is.available()];
            is.read(bytes);

//            设置响应头
            MultiValueMap<String, String> map = new HttpHeaders();
            map.add("Content-Disposition", "attachment;filename=" + name);

//            设置响应状态码
            int status = HttpStatus.HTTP_OK;

            is.close();

            return new ResponseEntity<>(bytes, map, status);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
